/**
 * @file    VGettyAMSlave.cpp
 * @brief   Slave tool for Device AnsweringMachineVGetty, used in script 
 *          calls.sh.
 *
 *          This command line program is called by bash (vm) shell script
 *          which defines rules and flow of vgetty.
 *
 ****************************************************************************
 * @version $Id: VGettyAMSlave.cpp 1708 2010-01-26 22:28:01Z alex $
 * @author  Alessandro Polo
 ****************************************************************************/
/* Copyright (c) 2009, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/

//--------------------------------------------------------------------------------
 #include <QCoreApplication>
 #include "VGettyAMSlave.h"
//--------------------------------------------------------------------------------

using namespace std;


// return 0 on success
// return 1 when action is unknown
// return 2 when sending failed
// return 3 when response failed (timed out)

int main(int argc, char* argv[])
{
	if ( argc < 3 ) { // less than 2 arguments
		printf ("WOSH Tool - AM vgetty slave " _VERSION " - UDP Message I/O - OpenSmartHome.com \n");
		printf ("---------------------------------------------------------------------------\n");
		printf("USE: " _PROGRAM " <ACTION> <COMMAND/DATA> [OPTIONS]\n\n");
		printf("Available Actions are:\n");
		printf(" - " _ACTION_SEND " : send a command/data to virtual device\n");
		printf(" - " _ACTION_SENDWAIT " _ send a command/data to virtual device and wait for response (which will be printed)\n");

		return 0;
	 }

	// setup parameters
	string action(argv[1]);
	string command(argv[2]);
	string destination = _DEVICE_ADDRESS;
	int port = _DEVICE_PORT;

	// init QT and UDP driver
	QCoreApplication app(argc, argv);
	UdpListener myListener;

	// ---------------------------------------------------------------------------------------------
	// sends a Command (data) to wosh Device
	if ( action == _ACTION_SEND ) {
		// command === data
		bool sent = myListener.sendDatagram( command.c_str(), command.length(), destination, port );
		if ( sent )
			return 0;	// all ok, exiting nicely
		else
			return 2;	// can't send, return a 'FAILED' exit code
	 }
	// ---------------------------------------------------------------------------------------------
	// sends a Command (data) to wosh Device and wait for response (will be printed to stdout)
	else if ( action == _ACTION_SENDWAIT ) {

		// concat arguments to get all data
		string data = "";
		for(int i=2; i<argc; i++) {
			data += string(argv[i]) + " ";
		 }
		
		// setup listener (open a second thread which act as UDP server, waiting response)
		myListener.initSocket();

		// send Command/data
		bool sent = myListener.sendDatagram( data.c_str(), data.length(), destination, port );
		if ( !sent ) {
			myListener.close();
			// can't send, return a 'FAILED' exit code
			return 2;
		 }

		// wait some seconds for response
		unsigned int i = 0;
		while( i++ < _LISTEN_WAIT_TIMEOUT ) {
			if ( myListener.messageCount > 0 )
				break;
			sleep(1);
		 }

		// we don't need to listen data anymore
		myListener.close();

		// reply timed out? then exit
		if ( myListener.messageCount == 0 ) {
			return 3;		// no response, return a 'FAILED' exit code
		 }

		// seems to be fine, print out the response
		printf( myListener.retData.c_str() );
		// all ok, exiting nicely
		return 0;
	 }
	// ---------------------------------------------------------------------------------------------

	// unknown command
	return 1;
}
